package deibay.server;

import java.util.HashMap;
import java.util.logging.Level;
import deibay.DeibayLogger;
import deibay.network.IClientCommunicator;
import deibay.server.events.Event;
import deibay.server.events.CreateSessionEvent;
import deibay.server.events.RemoveSessionEvent;
import deibay.server.io.XmlRegisteredUsers;
import deibay.server.network.Session;
import deibay.users.User;


/**
 * @author   Joel Cordeiro
 */
public class UserManager implements EventConsumer{

	private HashMap<String, User> loggedUsers = null;
	private XmlRegisteredUsers regist = null;
	
	public UserManager()
	{
		loggedUsers = new HashMap<String, User>();				
	}
	
	public void init()
	{
		regist = new XmlRegisteredUsers();
		regist.loadXmlRegister();
		subscribeToEvents();
	}
	
	private void subscribeToEvents() {		
		ServerManager.getInstance().getEventManager().subscribe(this, CreateSessionEvent.class);
		ServerManager.getInstance().getEventManager().subscribe(this, RemoveSessionEvent.class);
	}		
	
	public void logout(User user)
	{
		loggedUsers.remove(user);
	}
	
	public synchronized User authenticate(String login, String password)
	{
		User user = loggedUsers.get(login); 
		if(user != null)
			return user;
		else
			user = regist.getUser(login, password);
		return user;
	}
	
	public synchronized User register(String login, String password, String email, String address, String role)
	{			
		User user = regist.addRegister(login, password, email, address, role);		
		return user;
	}
		
	public synchronized void logon(User user)
	{
		this.loggedUsers.put(user.getId(), user);		
	}
	
	public boolean isLogged(User user)
	{
		return this.loggedUsers.containsKey(user.getId());
	}

	private synchronized void removeUser(User user)
	{		
		this.loggedUsers.remove(user.getId());
	}
	
	public void handleEvent(Event event) {
		if(event instanceof CreateSessionEvent)
		{
			User user = ((CreateSessionEvent)event).getNewSessionArgs().getUser();
			if(!isLogged(user))
				logon(user);
		}		
		else if(event instanceof RemoveSessionEvent)
		{
			User user = ((RemoveSessionEvent)event).getRemoveSessionEventArg().getSession().getUser();
			removeUser(user);
		}
	}		
}
